package com.sample.springbatch.job.sample.reader;

import com.sample.springbatch.model.RepayOrderInfo;
import org.apache.commons.lang3.time.DateUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.batch.item.database.JdbcPagingItemReader;
import org.springframework.batch.item.database.Order;
import org.springframework.batch.item.database.support.MySqlPagingQueryProvider;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.jdbc.core.RowMapper;

import javax.annotation.PostConstruct;
import javax.sql.DataSource;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.Map;

/**
 * Jdbc 分页读取数据库
 * @author zwg
 * @date 2017/8/8.
 */
public class RepayOrderJdbcPagingItemReader<T> extends JdbcPagingItemReader {

    public static final Logger logger = LoggerFactory.getLogger(RepayOrderJdbcPagingItemReader.class);

    @Autowired
    DataSource dataSource;

    @Value("#{jobParameters['bussDate']}")
    private String bussDate = "2017-09-13 00:00:00";

    public RepayOrderJdbcPagingItemReader() {
        setPageSize(15);
        setFetchSize(10);

        //不用添加select from where group by等关键字
        MySqlPagingQueryProvider provider = new MySqlPagingQueryProvider();
        provider.setSelectClause("id, user_id, product_id,contract_no,amount, repay_type,repay_method");
        provider.setFromClause("repay_order_info");
        provider.setWhereClause("buss_date=:bussDate");

        //排序字段是否是主键决定了 大数据分页的效率，主键会作为where条件的一部分
        Map<String,Order> sortKeysMap = new HashMap<>();
        sortKeysMap.put("id",Order.ASCENDING);
        provider.setSortKeys(sortKeysMap);

        setQueryProvider(provider);


        Map<String, Object> params = new HashMap<>();
        try{
            params.put("bussDate", DateUtils.parseDate(bussDate, "YYYY-MM-dd hh:mm:ss"));
        }catch (Exception e){

        }
        setParameterValues(params);

        setRowMapper(new RowMapper<RepayOrderInfo>() {
            @Override
            public RepayOrderInfo mapRow(ResultSet resultSet, int i) throws SQLException {
                if(resultSet==null){
                    return null;
                }
                RepayOrderInfo item = new RepayOrderInfo();
                item.setId(resultSet.getLong("id"));
                item.setUserId(resultSet.getString("user_id"));
                //logger.info("rowMapper i:{}",i);
                return item;
            }
        });
    }


    @PostConstruct
    public void init(){
        setDataSource(dataSource);

    }

}
